Page({
  data: {
    orders: [], // 所有订单数据
    orderStatusFilter: 'all', // 订单状态筛选条件
    filteredOrders: [], // 筛选后的订单数据
    refreshTimer: null, // 刷新定时器
    refreshInterval: 30000, // 30秒刷新一次
    isLoading: false,
    lastUpdatedTime: null
  },

  onLoad(options) {
    // 模拟加载订单数据，实际使用时应从服务器获取
    const orders = wx.getStorageSync('paidOrders') || [];
    const orderStatusFilter = options.orderStatusFilter ? decodeURIComponent(options.orderStatusFilter) : 'all';
    this.setData({ orders, orderStatusFilter }, () => {
      this.filterOrders();
      this.startAutoRefresh(); // 启动自动刷新
    });
  },

  onUnload() {
    this.stopAutoRefresh(); // 页面卸载时停止刷新
  },

  // 启动自动刷新
  startAutoRefresh() {
    this.stopAutoRefresh(); // 先停止已有的定时器
    this.data.refreshTimer = setInterval(() => {
      this.fetchRemoteOrders(); // 从服务器获取最新订单
    }, this.data.refreshInterval);
  },

  // 停止自动刷新
  stopAutoRefresh() {
    if (this.data.refreshTimer) {
      clearInterval(this.data.refreshTimer);
      this.data.refreshTimer = null;
    }
  },

  // 从服务器获取最新订单（实际项目中替换为API调用）
  fetchRemoteOrders() {
    // 如果正在加载中，则不重复请求
    if (this.data.isLoading) return;
    
    this.setData({ isLoading: true });
    
    // 模拟从服务器获取订单数据
    setTimeout(() => {
      const remoteOrders = wx.getStorageSync('paidOrders') || [];
      
      // 检查是否有订单状态变化
      const hasStatusChanged = this.checkStatusChanged(remoteOrders);
      
      this.setData({ 
        orders: remoteOrders,
        isLoading: false,
        lastUpdatedTime: new Date().toLocaleTimeString()
      }, () => {
        this.filterOrders();
        
        // 如果有状态变化，显示提示
        if (hasStatusChanged) {
          wx.showToast({
            title: '订单状态已更新',
            icon: 'success',
            duration: 1500
          });
        }
      });
    }, 800);
  },

  // 检查订单状态是否有变化
  checkStatusChanged(remoteOrders) {
    const localOrders = this.data.orders;
    
    // 如果本地没有订单，返回false
    if (localOrders.length === 0) return false;
    
    // 检查每个订单的状态是否有变化
    for (const remoteOrder of remoteOrders) {
      const localOrder = localOrders.find(order => order.orderNumber === remoteOrder.orderNumber);
      if (localOrder && localOrder.orderStatus !== remoteOrder.orderStatus) {
        return true;
      }
    }
    
    return false;
  },

  // 筛选订单
  filterOrders() {
    const { orderStatusFilter, orders } = this.data;
    if (orderStatusFilter === 'all') {
      this.setData({ filteredOrders: [...orders] });
      return;
    }
    const filtered = orders.filter(order => order.orderStatus === orderStatusFilter);
    this.setData({ filteredOrders: filtered });
  },

  // 切换订单状态筛选
  onStatusChange(e) {
    const status = e.currentTarget.dataset.status;
    this.setData({ orderStatusFilter: status }, () => this.filterOrders());
  },

  // 确认收货
  handleConfirmReceipt(e) {
    const orderNumber = e.currentTarget.dataset.ordernumber;
    
    const updatedOrders = this.data.orders.map((order) => {
      if (order.orderNumber === orderNumber) {
        // 同时更新订单状态和物流状态
        const updatedOrder = { 
          ...order, 
          orderStatus: '已完成' 
        };
        
        // 如果订单有物流信息，也更新物流状态
        if (updatedOrder.logisticsInfo) {
          updatedOrder.logisticsInfo.status = '已完成';
        }
        
        return updatedOrder;
      }
      return order;
    });
    
    this.setData({ orders: updatedOrders }, () => {
      console.log('更新后的订单列表:', this.data.orders);
      this.filterOrders(); // 重新筛选订单以更新页面
      wx.showToast({
        title: '确认收货成功',
        icon: 'success'
      });
      wx.setStorageSync('paidOrders', updatedOrders.filter(order => order.orderStatus !== '待支付'));
    });
  },

  // 取消订单
  handleCancelOrder(e) {
    const orderNumber = e.currentTarget.dataset.ordernumber;
    wx.showModal({
      title: '确认取消',
      content: '确定要取消该订单吗？',
      success: (res) => {
        if (res.confirm) {
          // 从订单列表中移除该订单
          const orders = this.data.orders.filter(order => order.orderNumber !== orderNumber);
          this.setData({ orders }, () => this.filterOrders());
          wx.setStorageSync('paidOrders', orders.filter(order => order.orderStatus !== '待支付'));
          wx.showToast({
            title: '订单已取消',
            icon: 'success'
          });
        }
      }
    });
  },

  // 处理支付，这里只是简单示例，实际需要调用支付接口
  handlePayment(e) {
    const orderNumber = e.currentTarget.dataset.ordernumber;
    console.log('处理支付，订单编号:', orderNumber);
    // 调用支付接口的代码
  },

  // 申请售后
  handleAfterSale(e) {
    const orderNumber = e.currentTarget.dataset.ordernumber;
    const updatedOrders = this.data.orders.map((order) => {
      if (order.orderNumber === orderNumber) {
        return { ...order, orderStatus: '售后中' };
      }
      return order;
    });
    this.setData({ orders: updatedOrders }, () => {
      console.log('申请售后后的订单列表:', this.data.orders);
      this.filterOrders(); // 重新筛选订单以更新页面
      wx.showToast({ title: '申请售后成功', icon: 'success' });
      wx.setStorageSync('paidOrders', updatedOrders.filter(order => order.orderStatus !== '待支付'));
    });
  },

  // 取消售后
  handleCancelAfterSale(e) {
    const orderNumber = e.currentTarget.dataset.ordernumber;
    const updatedOrders = this.data.orders.map((order) => {
      if (order.orderNumber === orderNumber) {
        return { ...order, orderStatus: '已完成' };
      }
      return order;
    });
    this.setData({ orders: updatedOrders }, () => {
      console.log('取消售后后的订单列表:', this.data.orders);
      this.filterOrders(); // 重新筛选订单以更新页面
      wx.showToast({ title: '取消售后成功', icon: 'success' });
      wx.setStorageSync('paidOrders', updatedOrders.filter(order => order.orderStatus !== '待支付'));
    });
  },

  // 评价订单
  handleEvaluate(e) {
    const orderNumber = e.currentTarget.dataset.ordernumber;
    wx.showModal({
      title: '订单评价',
      content: '',
      editable: true,
      success: (res) => {
        if (res.confirm) {
          if (res.content.trim() === '') {
            wx.showToast({
              title: '请输入评价内容',
              icon: 'none'
            });
            return;
          }
          const updatedOrders = this.data.orders.map((order) => {
            if (order.orderNumber === orderNumber) {
              return {
                ...order,
                orderStatus: '已评价',
                isEvaluated: true,
                evaluationText: res.content
              };
            }
            return order;
          });
          this.setData({ orders: updatedOrders }, () => {
            console.log('评价后的订单列表:', this.data.orders);
            this.filterOrders(); // 重新筛选订单以更新页面
            wx.showToast({
              title: '评价成功',
              icon: 'success'
            });
            wx.setStorageSync('paidOrders', updatedOrders.filter(order => order.orderStatus !== '待支付'));
          });
        }
      }
    });
  },

  // 查看订单详情
  viewOrderDetail(e) {
    const orderNumber = e.currentTarget.dataset.ordernumber;
    const orderInfo = this.data.orders.find(order => order.orderNumber === orderNumber);
    
    if (!orderInfo) {
      wx.showToast({ title: '订单信息获取失败', icon: 'none' });
      return;
    }
    
    // 记录点击时间，用于统计用户行为
    const clickTime = new Date().toISOString();
    console.log(`用户点击订单详情: ${orderNumber}, 时间: ${clickTime}`);
    
    const encodedOrderInfo = encodeURIComponent(JSON.stringify(orderInfo));
    wx.navigateTo({
      url: `/pages/OrderDetail/OrderDetail?orderInfo=${encodedOrderInfo}`
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.fetchRemoteOrders();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  }
});
